Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

257
Views
How to return null instead of undefined when using arr.map(elem => dict[elem]) in typescript?

I wrote a simple function to replace values in an array according to a look-up dictionary object:

// typescript
function recode(arr: any[], dict: Record<string, string> ) {
    return arr.map(el => dict[el])
}

It works as expected. However, I want the function to return null when array values have no match in the look-up dictionary.

So right now if I do:

// array input
const myArr: string[] = ['eggplant', 'tomato', 'carrot', 'cabbage'];

// look-up dictionary
const myDictionary: Record<string, string> = {
    eggplant: 'purple',
    tomato: 'red',
    carrot: 'orange'
};

function recode(arr: any[], dict: Record<string, string> ) {
    return arr.map(el => dict[el])
}

// calling recode()
recode(myArr, myDictionary) 
// returns 
// ["purple", "red", "orange", undefined] 

But I want the output to be

// ["purple", "red", "orange", null] 

Is there a simple enough way to achieve this, considering that I'm using typescript (not sure it makes a difference)?

Typescript REPL

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use the nullish coalescing operator (??) to resolve null in cases of undefined (and use a generic type parameter to infer the type of values from the dict parameter):

TS Playground

const myArr: string[] = ['eggplant', 'tomato', 'carrot', 'cabbage'];

const myDictionary: Record<string, string> = {
    eggplant: 'purple',
    tomato: 'red',
    carrot: 'orange'
};

function recode <T extends Record<string, any>>(
  arr: readonly string[],
  dict: T,
): (T[keyof T] | null)[] {
    return arr.map(el => dict[el] ?? null);
}

const result = recode(myArr, myDictionary); // (string | null)[]
console.log(result);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!